/*
 * @Author: your name
 * @Date: 2020-12-30 19:52:21
 * @LastEditTime: 2020-12-31 11:35:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \H5 2010 studyd:\H5 2010 练习\第三阶段 Vue + node\DAY 7\panda\src\store\modules\cart.js
 */
const cartItems = JSON.parse(localStorage.getItem('cart')) || []

export default {
  namespaced: true, // 启用命名空间(名字空间)
  state: {
    cartItems // 购物车数组
  },
  getters: {
    /**
     * 计算是否 所有商品都被选中
     * @param {*} state
     */
    allChecked(state) {
      return state.cartItems.every(curr => curr.checked)
    },
    // 计算总价
    totalMoney(state) {
      return state.cartItems.reduce((result, curr) => {
        if (curr.checked) {
          result += curr.price * curr.count
        }
        return result
      }, 0)
    },
    // 计算总数量
    totalCount(state) {
      return state.cartItems.reduce((result, curr) => (result += curr.count), 0)
    }
  },
  mutations: {
    add(state, payload) {
      // state.cartItems.push(payload)

      // 计算是否有一选购的当前商品存在
      const has = state.cartItems.some(curr => curr.id === payload.id)
      // 计算是否有已存在的当前商品，则修改数量即可
      if (has) {
        state.cartItems = state.cartItems.map(curr => {
          const copy = { ...curr }
          if (copy.id === payload.id) {
            copy.count += payload.count
          }
          return copy
        })
      } else {
        state.cartItems.push({
          ...payload,
          checked: true
        })
      }
    },
    // 删除购物车商品
    remove(state, payload) {
      state.cartItems = state.cartItems.filter(curr => curr.id !== payload)
    },
    // 修改购物车中商品数量
    modifyNum(state, { id, count }) {
      state.cartItems = state.cartItems.map(curr => {
        const copy = { ...curr }
        if (copy.id === id) {
          copy.count = count
        }
        return copy
      })
    },
    // 修改购物车中商品的选中状态
    changeChecked(state, payload) {
      state.cartItems = state.cartItems.map(curr => {
        const copy = { ...curr }
        if (copy.id === payload) {
          copy.checked = !copy.checked
        }
        return copy
      })
    },
    // 全选
    checkAll(state, payload) {
      // payload 中保存的是修改后的选中状态值
      state.cartItems = state.cartItems.map(curr => {
        const copy = { ...curr }
        copy.checked = payload
        return copy
      })
    }
  },
  actions: {}
}
